<template>
  <div style="height: 100%">
    <el-container style="background-color:#fff; height:100%; overflow:hidden;">
      <el-header class="file_header" style="height: 50px">
        <el-row :gutter="20" style="width:100%">
          <el-col :span="12" class="header_title">
            <el-breadcrumb separator-class="el-icon-arrow-right" style="float:left;overflow: hidden">
              <el-breadcrumb-item v-for="(item,index) in headerData" :key="index" >{{item}}</el-breadcrumb-item>
            </el-breadcrumb>
          </el-col>
          <el-col :span="12">
            <div style="float:right" class="search">
              <el-input v-model="search" size="small" style="width:250px" @keyup.enter.native='searchFile' placeholder="请输入内容">
                <el-button slot="append" style="cursor: pointer;" @click="searchFile">
                  <i class="el-icon-search"></i>
                </el-button>
              </el-input>

              <div style="float:right" class="btn_box">
                <el-tooltip effect="dark" content="图标" placement="top-start">
                  <span class="btns" :class="!showType ? 'icon_active': ''" @click="showType = !showType">
                    <i class="icon-icon"></i>
                  </span>
                </el-tooltip>

                <el-tooltip  effect="dark" content="列表" placement="top-start">
                  <span class="btns" :class="showType ? 'icon_active': ''" @click="showType = !showType">
                    <i class="icon-liebiao1"></i>
                  </span>
                </el-tooltip>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-header>
      <ul>
        <li style="display: flex;align-items: center;font-size: 12px;color: #232323;margin-bottom: 8px"
            v-for="item,index in common.percent" :key="index" v-show="item.percent!=100&&item.percent!=0">
          {{item.title}}上传进度：
          <el-progress size="mini" :stroke-width="5"
                       :percentage="item.percent" style="width: 200px;"></el-progress>
        </li>
      </ul>
      <el-container style="position:relative;height:100%">
        <el-main>
          <div class="content_main">
            <div class="file_content" @contextmenu.prevent="showMenu" >
              <el-table
                :data="showData"
                v-show="showType"
                stripe
                border
                node-key="id"
                @row-dblclick="dbClick"
                @row-contextmenu="rightClick"
                style="width: 100%">
                <el-table-column
                  label="文件名">
                  <template slot-scope="scope">
                    <p>{{scope.row.folderName}}</p>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="attributes.uploadTime"
                  label="上传日期">
                </el-table-column>
                <el-table-column
                  label="类型">
                  <template  slot-scope="scope">
                    <div>
                    <span v-if="scope.row.fileExt == ''">
                      folder
                    </span>
                      <span v-if="scope.row.fileExt !== ''">
                      {{scope.row.fileExt}}
                    </span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="size"
                  label="大小">
                </el-table-column>
              </el-table>
              <div class="iconList" v-show="!showType" >
                <el-row :gutter="20">
                  <el-col :span="3" v-if="jurisdiction.file_upload">
                    <div style="padding-left:14px; text-align: center" class="grid-content">

                      <div class="avatar-uploader" style="border: 1px dashed #8c939d;border-radius: 6px;;display: flex;align-items: center;justify-content: center;">
                        <i class="el-icon-plus avatar-uploader-icon" @click="changeFile(1)"></i>
                        <!--   文件上传  -->
                        <input ref="inputFile" id="upload_file" multiple type="file"  style="display: none" @change="getFile($event)"/>
                        <!-- 预览图上传 -->
                        <input ref="inputPreview" id="upload_preview" type="file" accept="image/*"  style="display: none" @change="getPreview($event)"/>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="3" v-for="(item, index) in showData" :key="index">
                    <div class="grid-content"  @dblclick="changeData(item)" style="user-select: none" :class="{'active_box': active==item.id}" :ref="item.id" @contextmenu.prevent="showMenu($event, item)" :value="item.value" :alt="item.parentDir" :type="item.fileExt"  :title="fileTooltip(item)">
                      <div class="rightullidiv" v-if="item.fileExt.toLowerCase() == 'mp4' || item.fileExt.toLowerCase() == 'ogg' || item.fileExt.toLowerCase() == 'webm' || item.fileExt.toLowerCase() == 'jpg' || item.fileExt.toLowerCase() == 'jpeg' || item.fileExt.toLowerCase() == 'png' || item.fileExt.toLowerCase() == 'gif'">
                        <img :src="item.previewUrl !== '' ? item.previewUrl : defaultPreviewUrl" class="rightulliimg" v-if="item.fileExt.toLowerCase() == 'mp4' || item.fileExt.toLowerCase() == 'ogg' || item.fileExt.toLowerCase() == 'webm'"/>

                        <img :src="item.url" class="rightulliimg" v-if="item.fileExt.toLowerCase() == 'jpg' || item.fileExt.toLowerCase() == 'jpeg' || item.fileExt.toLowerCase() == 'png' || item.fileExt.toLowerCase() == 'gif'"/>
                      </div>
                      <div v-else>
                        <svg class="icon" aria-hidden="true" v-if="item.fileExt == ''">
                          <use xlink:href="#icon-folder" class="svg"></use>
                        </svg>
                        <svg class="icon" aria-hidden="true" v-if="item.fileExt !== ''">
                          <use :xlink:href="'#icon-' + item.icon"></use>
                        </svg>
                      </div>
                      <p class="folderName">{{item.folderName}}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-main>
        <div id="menu" v-show="right_menu" ref="right_menu" :class="menuClass">
          <ul>
            <li @click="clone" v-if="isClone && jurisdiction.file_copy">
              <span class="icon-copy"></span>
              复制
            </li>
            <li @click="edit()" v-if="isShear && jurisdiction.file_shear">
              <span class="icon-jianqie"></span>
              剪切</li>
            <li @click="paste" v-if="isPaste && jurisdiction.file_paste">
              <span class="icon-niantie"></span>
              粘贴</li>
            <li @click="addFolder" v-if="createDirectory && jurisdiction.file_create">
              <span class="icon-wenjian"></span>
              创建目录</li>
            <li @click="remove" v-if="isRemove && jurisdiction.file_delete">
              <span class="icon-delete_icon"></span>
              删除</li>
            <li @click="rename" v-if="isRename && jurisdiction.file_rename">
              <span class="icon-bianji"></span>
              重命名</li>
            <li @click="editPreview" v-if="isEditPreview">
              <span class="icon-tihuan" style="margin-right: 1px"></span>
              <span>替换预览图</span>
            </li>
            <li @click="changeFile(0)" v-if="isUpload && jurisdiction.file_upload">
              <span class="icon-unie123"></span>
              <span>上传</span>
            </li>
            <li v-if="isDown" @click="preview">
              <span class="icon-unie122"></span>
              <span>下载</span>
            </li>
          </ul>
        </div>
      </el-container>
    </el-container>

    <CloundUp ref="indexElse" accept="jpg"></CloundUp>

    <div id="showVideo" style="display: none">
    </div>
    <img src="" id="image" style="display: none"/>
  </div>
</template>
<script>
    import { reName, removeFile, copyFile, addFileFolder, getTabList, searchFile, removeFolder, copyFolder, fireExists, newUploadFile, editPreview, downloadFile} from '@/api/file'
    import {uploadText} from "@/api/mail/write";
    import {uploadOss} from '@/util/file'
    import {getToken} from '@/util/auth'
    import website from '@/config/website';
    import {Base64} from 'js-base64';
    import {trim} from '@/util/util'
    import {mapGetters, mapState} from "vuex";
    import CloundUp from '@/components/product/DialogColund'
    export default {
        components:{
            CloundUp
        },
        data() {
            return {
                defaultPreviewUrl:'http://zhilubt.oss-cn-hangzhou.aliyuncs.com/ERPSAAS/%E6%B5%99%E6%B1%9F%E7%9B%B4%E8%B7%AF%E7%BD%91%E7%BB%9C%E7%A7%91%E6%8A%80/Test/imges/2020/04/20/big/09275/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20200420150921.png',
                fileName:'',
                fileUrl:'',
                showProgress:false,
                percent:0,
                menuClass:'',
                jurisdiction:{}, // 权限集合
                Flag: true, // 上传进度条
                UploadPercent: '', // 上传进度
                showType: false,
                right_menu: false,
                asideWdith: 250,
                expand: true, // 默认为关闭
                open: true,
                fileData: [], // 左侧侧边栏data
                headerData: ['自建目录'], // 头部面包屑
                data: [], // 后台返回的data
                showData: [], // 右侧显示的data
                defaultProps: {
                    children: 'children',
                    label: 'folderName'
                },
                search: '',
                disList: [],
                active: '',
                moveActive: false,
                positionX:0,
                positionY:0,
                nowData: '',
                copyName: '',
                copyPath: '',
                pastePath: '',
                file: '',
                copyItem: '',
                downPath: '',
                removeIcon: '',
                isPreview: false, // 预览
                isClone: false, // 克隆
                isShear: false, // 剪切
                isPaste: false, // 粘贴
                createDirectory: false, //创建目录,
                isRemove: false, // 删除
                isRename: false, // 重命名
                isUpload: false, // 上传
                isDown: false, // 下载
                isEditPreview: false, // 修改预览图
                headervalue: '',
                copyFileId: '', // 复制的文件id
                header: {
                },
                pasteType: '',
                copyValue: '',
                activePosition: '',
                iconData: ['dotm', 'avi', 'pptx', 'wma', 'xlsx', 'ppt', 'doc', 'folder', 'mp3', 'zip', 'ogg', 'txt', 'exe', 'psd', 'cad', 'img', 'pdf', 'docx', 'rar', 'webm', 'mp4', 'xls', 'dotx'],
                copyType: '',
                screenWidth: document.documentElement.clientWidth, // 屏幕宽度
                screenHeight: document.documentElement.clientHeight, // 屏幕高度
                isExpanded: true, // 默认展开全部节点
                isshare: false,
                cloneType:false,
                fileList:[],
                config:{
                    accessid: '',
                    policy: '',
                    signature: '',
                    dir: '',
                    host: '', // 上传阿里云地址
                    expire: '', // 过期时间戳
                    callback: ''
                },
                testSrc:''
            }
        },
        computed: {
            ...mapGetters(["permission"]),
            ...mapState(['common'])
        },
        created() {
            this.jurisdiction = this.vaildData(this.permission)
            if (this.$route.query.path) {
                this.fileType = this.$route.query.path
                this.headervalue = this.$route.query.path
                let arr = this.$route.query.path.split('/')
                this.headerData = arr.filter(d=>d) // filter 过滤空格

                getTabList(this.fileType).then((res) => {
                    if (res.data.success) {
                        res.data.data.forEach((value) => {
                            value.size = value.attributes.fileSize
                            if (this.iconData.includes(value.fileExt)) {
                                value.icon = value.fileExt
                            }  else {
                                console.log(value.icon)
                                value.icon = 'other'
                            }
                        })
                        this.showData = []
                        res.data.data.forEach((value, index) => {
                            if(index > 0) {
                                this.showData.push(value)
                            }
                        })
                        this.nowData = res.data.data[0]
                    }
                })
            } else {
                getTabList('自建目录/').then((res) => {
                    if (res.data.success) {
                        res.data.data.forEach((value) => {
                            value.size = value.attributes.fileSize
                            if (this.iconData.includes(value.fileExt)) {
                                value.icon = value.fileExt
                            }  else {
                                value.icon = 'other'
                            }
                        })
                        this.showData = []
                        res.data.data.forEach((value, index) => {
                            if(index > 0) {
                                this.showData.push(value)
                            }
                        })
                        this.nowData = res.data.data[0]
                    }
                })
            }

        },
        mounted() {
            document.body.addEventListener('click', () => {
                this.right_menu = false
            })
            document.body.addEventListener('contextmenu', () => {
                this.bus.$emit('contextmenu')
                this.right_menu = false
            })
            this.bus.$on('closeFileMenu', () => {
                this.right_menu = false
                this.search = ''
            })

            this.bus.$on('removeFile', (value, parentDir, pid) => {
                if (value == this.$route.query.path) { // 删除了当前目录
                    this.$router.push({
                        path: '/file/index',
                        query: {
                            path: parentDir,
                            id: pid
                        }
                    })
                } else { // 删除非当前
                    getTabList(this.$route.query.path).then((res) => {
                        if (res.data.success) {
                            res.data.data.forEach((value) => {
                                value.size = value.attributes.fileSize
                                if (this.iconData.includes(value.fileExt)) {
                                    value.icon = value.fileExt
                                }  else {
                                    value.icon = 'other'
                                }
                            })
                            this.showData = []
                            res.data.data.forEach((value, index) => {
                                if(index > 0) {
                                    this.showData.push(value)
                                }
                            })
                        }
                    })
                }
            })

            this.bus.$on('updataFile', () => { // 更新页面
                console.log('刷新')
                getTabList(this.$route.query.path).then((res) => {
                    let arr = this.$route.query.path.split('/')
                    this.headerData = arr.filter(d=>d)
                    if (res.data.success) {
                        res.data.data.forEach((value) => {
                            value.size = value.attributes.fileSize
                            if (this.iconData.includes(value.fileExt)) {
                                value.icon = value.fileExt
                            }  else {
                                value.icon = 'other'
                            }
                        })
                        this.showData = []
                        res.data.data.forEach((value, index) => {
                            if(index > 0) {
                                this.showData.push(value)
                            }
                        })
                    }
                })
            })

            this.header['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
            this.header['Blade-Auth'] = 'bearer ' + getToken();
        },
        methods: {
            fileTooltip(item) {
                /** 设置换行时，手动输入enter键，设置换行 **/
                var title = `作者：${item.attributes.userName}
文件名称：${item.folderName}
文件大小：${item.attributes.fileSize}
上传时间：${item.uploadTime}`
                return  title
            },
            openFile() {
                this.$refs.indexElse.init()
            },
            changeFile(type) {
                if(type) {
                    this.nowData.value = this.headerData.join('/') + '/'
                }
                document.getElementById('upload_file').click()
            },
            captureImage(file) {
                var video = document.getElementById("video");
                var canvas = document.createElement("canvas");
                setTimeout(() => {
                    canvas.getContext("2d").drawImage(video, 0, 0, 300, 400);
                    var img = document.getElementById("image");
                    img.src = canvas.toDataURL("image/jpg");
                    // 后端上传第一帧预览图
                    var dataurl = canvas.toDataURL("image/png");
                    var arr = dataurl.split(','),
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    var newFile = new File([u8arr], `${Date.now()}.png`, {type: 'image/jpeg', lastModified: Date.now()});
                    let formData = new FormData();
                    formData.append("file",newFile);

                    uploadText(formData).then(res => {
                        this.upload(file, res.data.data[0].fileUrl)
                    }).catch((err)=>{
                        console.log(err)
                    })
                }, 1000)
            },
            getImg (file) {
                var url = URL.createObjectURL(file);
                var showVideo = document.getElementById("showVideo");

                var htmls = ' <video width="50%" id="video" height="auto" autoplay="autoplay" muted controls> <source src="' + url + '">您的浏览器不支持 HTML5 video 元素。</video>';
                showVideo.innerHTML = htmls;
                let _this = this
                document.getElementById("video").addEventListener("canplay", function () {
                    _this.captureImage(file)
                }(file))
            },
            upload(file, previewUrl) {
                let fileSize = file.size / 1024 / 1024
                if (fileSize < 200) {
                    var form = new FormData()
                    form.append('folderName', this.nowData.value)
                    form.append('fileName', file.name)
                    fireExists(form).then(res => {
                        if (!res.data.data) {
                            uploadOss(file).then(result => {
                                if(result.url) {
                                    let form = new FormData();
                                    form.append("folderName", this.nowData.value);
                                    form.append("isshare", this.nowData.isshare);
                                    form.append("fileName", file.name);
                                    form.append("fileSize", file.size);
                                    form.append("fileOsskey", result.fileKey);
                                    form.append("fileUrl", result.url);
                                    form.append("previewUrl", previewUrl ? previewUrl : '');
                                    newUploadFile(form).then(res => {
                                        if (res.data.success) {
                                            this.$message({
                                                message: res.data.data,
                                                type: 'success'
                                            })
                                            this.bus.$emit('updataFIleMenu', this.nowData.id)
                                            this.refresh(this.nowData.parentDir) // 重新刷新
                                            var inputDOM = this.$refs.inputFile;
                                            inputDOM.value = null
                                        }
                                    })
                                } else {
                                    this.$message({
                                        message: '网络不稳定，请稍候再试',
                                        type: "success"
                                    })
                                    event.target.value = null
                                }
                            })
                        } else {
                            this.$message({
                                message: '上传文件名和该文件夹下文件重名',
                                type: "success"
                            })
                            event.target.value = null
                        }
                    })
                } else{
                    this.$message({
                        message: '您要上传的文件大小超过200M',
                        type: "success"
                    })
                    event.target.value = null
                }
            },
            getFile(event) {
                var files = event.target.files
                for(var i = 0; i<files.length; i++) {
                    /** 判断是否重名 **/
                    let switchType = true
                    let file = event.target.files[i]
                    if (this.common.percent.length > 0) {
                        this.common.percent.forEach(value => {
                            if (value.title === file.name) {
                                switchType = false
                            }
                        })
                    } else {
                        switchType = true
                    }

                    if (switchType) {
                        // 异步操作，改为同步
                        let fileType = file.type
                        if (fileType == 'audio/ogg' || fileType == 'video/webm' || fileType == 'video/mp4') {
                            this.getImg(file)
                        } else {
                            this.upload(file)
                        }
                    } else {
                        this.$message({
                            message: '所选文件有重名，无法上传',
                            type: "success"
                        })
                        event.target.value = ''
                    }
                }
            },
            editPreview() {
                document.getElementById('upload_preview').click()
            },
            getPreview(event) {
                let file = event.target.files[0]
                let formData = new FormData();
                formData.append("file",file);
                uploadText(formData).then(res => {
                    editPreview(this.nowData.fileId, res.data.data[0].fileUrl).then(res => {
                        this.refresh()
                    })
                }).catch((err)=>{
                    console.log(err)
                })

            },
            refresh() {
                getTabList(this.$route.query.path || '自建目录/').then((res) => {
                    if (res.data.success) {
                        res.data.data.forEach((value) => {
                            value.size = value.attributes.fileSize
                            if (this.iconData.includes(value.fileExt)) {
                                value.icon = value.fileExt
                            }  else {
                                value.icon = 'other'
                            }
                        })
                        this.showData = []
                        res.data.data.forEach((value, index) => {
                            if(index > 0) {
                                this.showData.push(value)
                            }
                        })
                        this.search = ''
                    }
                })
            },
            verification(str) {
                var cat = /[`&*<>:"{}|,\/\\[\]·*：]/im
                return !cat.test(str)
            },
            rename() { // 重命名
                this.$prompt('请输入新名称', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator: this.verification,
                    inputErrorMessage:"文件名称不允许出现特殊字符",
                    inputValue: this.nowData.folderName
                }).then(({ value }) => {
                    value = trim(value)
                    if(value != '') {
                        var isFile = ''
                        if(this.nowData.fileExt == '') {
                            isFile = '1'
                        } else {
                            isFile = '0'
                        }

                        if(value !== this.nowData.folderName) {
                            reName(this.nowData.parentDir, value, this.nowData.folderName, isFile).then((res) =>{
                                if (res.data.success) {
                                    this.$message({
                                        type: 'success',
                                        message: res.data.msg
                                    });
                                    this.refresh() // 手动再次获取数据
                                    this.bus.$emit('updataFIleMenu', this.nowData.id)
                                }
                            })
                        }
                    } else {
                        this.$message('目录名不能为空');
                    }
                })
            },
            remove() { // 删除
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    if (this.nowData.fileExt !== '') { // 文件
                        removeFile(this.nowData.fileId).then((res) => {
                            if (res.data.success) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.refresh()
                            }
                        })
                    } else { // 文件夹
                        removeFolder(this.nowData.value).then((res) =>{
                            if (res.data.success) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.refresh()
                                this.bus.$emit('updataFIleMenu', this.nowData.id)
                            }
                        })
                    }
                })
            },
            edit() { //剪切
                this.cloneType = true
                this.pasteType = 'shear'
                this.copyName = this.nowData.parentDir // 来源父文件
                this.copyValue = this.nowData.folderName
                this.copyType = this.nowData.fileExt
                this.copyPath = this.nowData.value // 文件
                this.copyFileId = this.nowData.fileId // 文件id
            },
            preview() { // 预览
                // window.open(this.nowData.url) // 打开新页面预览 (下载)
                downloadFile(this.nowData.fileId).then(res => {
                    var blob = new Blob([res.data]); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
                    var downloadElement = document.createElement('a');
                    var href = window.URL.createObjectURL(blob); // 创建下载的链接
                    downloadElement.href = href;

                    downloadElement.download = this.nowData.folderName; // 下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); // 点击下载
                    document.body.removeChild(downloadElement); // 下载完成移除元素
                    window.URL.revokeObjectURL(href); // 释放掉blob对象
                })
            },
            clone() { // 复制
                this.cloneType = true
                this.pasteType = 'clone'
                this.copyName = this.nowData.parentDir // 来源父文件
                this.copyValue = this.nowData.folderName
                this.copyType = this.nowData.fileExt
                this.copyPath = this.nowData.value // 文件
                this.copyFileId = this.nowData.fileId // 文件id
            },
            paste() { // 粘贴
                if(this.cloneType) {
                    if(this.copyType !== '') { // 文件
                        copyFile(this.nowData.value  + this.copyValue, this.copyName, this.copyPath).then((res) => {
                            if (res.data.success) {
                                if (this.pasteType == 'clone'){
                                    this.refresh()
                                } else {
                                    removeFile(this.copyFileId).then((res) => {
                                        if (res.data.success) {
                                            this.refresh()
                                        }
                                    })
                                }
                            }
                        })
                    } else {
                        this.pastePath = this.nowData.value //复制到
                        copyFolder(this.pastePath, this.copyPath).then(res => {
                            if (res.data.success) {
                                this.$message({
                                    message:res.data.msg,
                                    type:'success'
                                })
                                if (this.pasteType == 'clone') {
                                    this.refresh()
                                    this.bus.$emit('updataFIleMenu', this.nowData.id)
                                } else {
                                    removeFolder(this.copyPath).then((res) =>{
                                        if (res.data.success) {
                                            this.refresh()
                                            this.bus.$emit('updataFIleMenu', this.nowData.id)
                                        }
                                    })
                                }
                            }
                        })
                    }

                    this.$router.push({
                        path: '/file/index',
                        query: {
                            path: this.nowData.value
                        }
                    })
                    this.cloneType = false
                } else {
                    this.$message({
                        type:'warning',
                        message:'请选择粘贴内容'
                    })
                }

            },
            addFolder() { // 新建文件夹
                this.$prompt('请输入目录名', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValidator: this.verification,
                    inputErrorMessage:'文件名称不允许出现特殊字符'
                }).then(({ value }) => {
                    if (value) {

                        if(this.nowData.value.split('/').length - 1 > 4) {
                            this.$message('目录层级请控制在5层以内')
                        } else {
                            value = trim(value)
                            if (value != '') {
                                addFileFolder(value, this.nowData.value, this.nowData.isshare).then((res) => {
                                    if (res.data.success) {
                                        this.$message({
                                            type: 'success',
                                            message: res.data.msg
                                        });

                                        this.bus.$emit('updataFIleMenu', this.nowData.id)

                                        this.refresh(this.nowData.id) // 手动再次获取数据
                                    }
                                })
                            }
                        }
                    } else {
                        this.$message('目录名不能为空');
                    }
                })
            },
            dbClick(item) { // 表格双击
                this.nowData = item
                if (item.fileExt == '') {
                    // 点击变化头部面包屑
                    this.headervalue = item.value
                    let arr = item.value.split('/')
                    this.headerData = arr.filter(d=>d)
                    this.bus.$emit('updataFIleMenu', item.id)
                    this.$router.push({
                        path: '/file/index',
                        query: {
                            path: item.value
                        }
                    })
                    this.search = ''
                } else {
                    this.preview()
                }
            },
            error(err) {
                this.$message({
                    type:'error',
                    message: err.data.msg
                })
            },
            rightClick(row, column, event) { // 右键
                this.activePosition = 'right'
                this.bus.$emit('contextmenu')
                event.preventDefault() // 配合使用，组织默认事件，同时组织事件冒泡
                event.cancelBubble = true
                this.$refs.right_menu.style.left = event.pageX  + 'px'
                this.$refs.right_menu.style.top = event.pageY  + 'px'

                this.nowData =  JSON.parse(JSON.stringify(row))
                if(row.fileExt == '') { // 文件夹
                    this.activePosition = 'right'
                    this.isPreview = false, // 预览
                        this.isClone = true, // 克隆
                        this.isShear = true, // 剪切
                        this.isPaste = true, // 粘贴
                        this.createDirectory = true, //创建目录,
                        this.isRemove = true, // 删除
                        this.isRename = true, // 重命名
                        this.isUpload = true, // 上传
                        this.isDown = false // 下载
                    this.isEditPreview = false
                } else { // 文件

                    if(row.fileExt.toLowerCase() == 'mp4' || row.fileExt.toLowerCase() == 'webm' || row.fileExt.toLowerCase() == 'ogg') {
                        this.isEditPreview = true // 修改预览图
                    } else {
                        this.isEditPreview = false // 修改预览图
                    }
                    this.activePosition = 'right'
                    this.isPreview = true, // 预览
                        this.isClone = true, // 克隆
                        this.isShear = true, // 剪切
                        this.isPaste = false, // 粘贴
                        this.createDirectory = false, //创建目录,
                        this.isRemove = true, // 删除
                        this.isRename = true, // 重命名
                        this.isUpload = false, // 上传
                        this.isDown = true // 下载
                }

                if ( row != undefined && row.attributes.currentUser != row.attributes.createUser) {
                    this.isRemove = false
                    this.isRename = false
                    this.isClone = false, // 克隆
                        this.isShear = false // 剪切
                    this.isEditPreview = false
                }


                this.right_menu = true
                this.$refs.right_menu.style.left = event.x  + 'px'
                this.$refs.right_menu.style.top = event.y  + 'px'

                // alert(menuWidth)
                this.$nextTick(() => {
                    let menuWidth = this.$refs.right_menu.clientWidth || this.$refs.right_menu.offsetWidth // 菜单宽度
                    let menuHeight = this.$refs.right_menu.clientHeight || this.$refs.right_menu.offsetHeight // 菜单高度
                    if (event.x + menuWidth > this.screenWidth) { // 达到右侧宽度边界
                        this.$refs.right_menu.style.left = this.screenWidth - menuWidth  + 'px'
                    }
                    if (event.y + menuHeight > this.screenHeight) { // 达到下侧高度边界
                        this.$refs.right_menu.style.top = this.screenHeight - menuHeight  + 'px'
                    }
                })
            },
            progress(event, file) {
                this.Flag = true;
                this.UploadPercent = file.percentage.toFixed(0);

            },
            showMenu(event, item) { //图标的右键
                this.bus.$emit('contextmenu')
                event.preventDefault() // 配合使用，组织默认事件，同时组织事件冒泡
                event.cancelBubble = true
                if (typeof item == 'undefined') {
                    this.nowData.value = this.headerData.join('/') + '/'
                    console.log(item)
                    this.isPreview = false, // 预览
                        this.isClone = false, // 克隆
                        this.isShear = false, // 剪切
                        this.isPaste = true, // 粘贴
                        this.createDirectory = true, //创建目录,
                        this.isRemove = false, // 删除
                        this.isRename = false, // 重命名
                        this.isUpload = true, // 上传
                        this.isDown = false // 下载
                    this.isEditPreview = false
                } else {
                    this.nowData =  JSON.parse(JSON.stringify(item))
                    if(item.fileExt == '') { // 文件夹
                        this.activePosition = 'right'
                        this.isPreview = false, // 预览
                            this.isClone = true, // 克隆
                            this.isShear = true, // 剪切
                            this.isPaste = true, // 粘贴
                            this.createDirectory = true, //创建目录,
                            this.isRemove = true, // 删除
                            this.isRename = true, // 重命名
                            this.isUpload = true, // 上传
                            this.isDown = false // 下载
                    } else { // 文件

                        if(item.fileExt.toLowerCase() == 'mp4' || item.fileExt.toLowerCase() == 'webm' || item.fileExt.toLowerCase() == 'ogg') {
                            this.isEditPreview = true // 修改预览图
                        } else {
                            this.isEditPreview = false // 修改预览图
                        }

                        this.activePosition = 'right'
                        this.isPreview = true, // 预览
                            this.isClone = true, // 克隆
                            this.isShear = true, // 剪切
                            this.isPaste = false, // 粘贴
                            this.createDirectory = false, //创建目录,
                            this.isRemove = true, // 删除
                            this.isRename = true, // 重命名
                            this.isUpload = false, // 上传
                            this.isDown = true // 下载
                    }
                }

                if ( item != undefined && item.attributes.currentUser != item.attributes.createUser) {
                    this.isRemove = false
                    this.isRename = false
                    this.isClone = false, // 克隆
                        this.isShear = false // 剪切
                    this.isEditPreview = false
                }

                this.right_menu = true

                this.$refs.right_menu.style.left = event.x  + 'px'
                this.$refs.right_menu.style.top = event.y  + 'px'

                this.$nextTick(() => {
                    let menuWidth = this.$refs.right_menu.clientWidth || this.$refs.right_menu.offsetWidth // 菜单宽度
                    let menuHeight = this.$refs.right_menu.clientHeight || this.$refs.right_menu.offsetHeight // 菜单高度
                    if (event.x + menuWidth > this.screenWidth) { // 达到右侧宽度边界
                        this.$refs.right_menu.style.left = this.screenWidth - menuWidth  + 'px'
                    }
                    if (event.y + menuHeight > this.screenHeight) { // 达到下侧高度边界
                        this.$refs.right_menu.style.top = this.screenHeight - menuHeight  + 'px'
                    }
                })
            },
            editasideWdith(width) {
                this.asideWdith = width
                this.open = !this.open
            },
            success() {
                this.videoFlag = false
                this.bus.$emit('updataFIleMenu', this.nowData.id)
                this.refresh(this.nowData.parentDir) // 重新刷新
            },
            searchFile() { // 右上角搜索
                searchFile(this.search, this.nowData.value).then((res) => {
                    // console.log(res)
                    this.nowData = res.data.data[0]
                    res.data.data.forEach((value) => {
                        value.size = value.attributes.fileSize
                        if (this.iconData.includes(value.fileExt)) {
                            value.icon = value.fileExt
                        }  else {
                            value.icon = 'other'
                        }
                    })
                    this.showData = []
                    res.data.data.forEach((value, index) => {
                        if(index > 0) {
                            this.showData.push(value)
                        }
                    })
                })
            },

            parte (value, parentvalue, fileExt, source) {
                if (value == source) { // 处理为相同文件夹
                    return
                }
                if (parentvalue == source) { // 处理父文件夹复制到子文件夹
                    this.$message({
                        message: '目标文件夹是源文件夹的子文件夹',
                        type: 'error'
                    })
                    return
                }
                if (fileExt !== '') { // 处理所复制到的文件地址是图片
                    return
                }
                copyFile(value, '', source).then((res) => {
                    if (res.data.success) {
                        removeFile(this.nowData.fileId).then(() => {
                            this.refresh()
                        })
                    }
                    // 删除
                })
            },
            changeData(item) { //右侧双击
                this.nowData = item
                if (item.fileExt == '') {
                    // 点击变化头部面包屑
                    this.headervalue = item.value
                    let arr = item.value.split('/')
                    this.headerData = arr.filter(d=>d)
                    this.bus.$emit('updataFIleMenu', item.id)
                    this.$router.push({
                        path: '/file/index',
                        query: {
                            path: item.value
                        }
                    })
                    this.search = ''
                } else {
                   this.preview()
                }
            },
            nodeClick(value) { // tre点击
                this.right_menu = false
                getTabList(value.value).then((res)=> {
                    if (res.data.success) {
                        this.nowData = res.data.data[0]
                        res.data.data.forEach((value) => {
                            value.size = value.attributes.fileSize
                            if (this.iconData.includes(value.fileExt)) {
                                value.icon = value.fileExt
                            }  else {
                                value.icon = 'other'
                            }
                        })
                        this.showData = []
                        res.data.data.forEach((value, index) => {
                            if(index > 0) {
                                this.showData.push(value)
                            }
                        })

                    }
                })
                // this.showData = value.data
                // 点击变化头部面包屑
                this.headervalue = value.value
                let arr = value.value.split('/')
                this.headerData = arr.filter(d=>d) // filter 过滤空格
                // console.log(this.headerData)
            }
        },
        watch:{
            right_menu(value) {
                if(!this.isDown&& !this.jurisdiction.file_upload && !this.jurisdiction.file_rename && !this.jurisdiction.file_delete && !this.jurisdiction.file_create && !this.jurisdiction.file_paste && !this.jurisdiction.file_copy && !this.jurisdiction.file_shear) {
                    this.menuClass = 'border_none'
                } else {
                    this.menuClass = ''
                }
            },
            input1(value) {
                let arr = []
                this.showData.forEach((element) => {
                    if (element['value'].split('').indexOf(value) > -1) {
                        arr.push(element)
                    }
                })
                this.showData = arr
            },
            expand() {
                for(var i=0;i<this.$refs.tree.store._getAllNodes().length;i++){ // 监听 expand变化，改变tree的展开与关闭
                    this.$refs.tree.store._getAllNodes()[i].expanded = this.expand;
                }
            },
            '$route.query.path': function(value) {
                if (value) {
                    getTabList(value).then((res) => {
                        if (res.data.success) {
                            res.data.data.forEach((value) => {
                                value.size = value.attributes.fileSize
                                if (this.iconData.includes(value.fileExt)) {
                                    value.icon = value.fileExt
                                }  else {
                                    value.icon = 'other'
                                }
                            })
                            this.showData = []
                            res.data.data.forEach((value, index) => {
                                if(index > 0) {
                                    this.showData.push(value)
                                }
                            })
                            this.nowData = res.data.data[0]
                            this.bus.$emit('checkFile', this.nowData)
                        }
                        let arr = value.split('/')
                        this.headerData = arr.filter(d=>d)
                    })
                } else {
                    getTabList('自建目录/').then((res) => {
                        if (res.data.success) {
                            res.data.data.forEach((value) => {
                                value.size = value.attributes.fileSize
                                if (this.iconData.includes(value.fileExt)) {
                                    value.icon = value.fileExt
                                }  else {
                                    value.icon = 'other'
                                }
                            })
                            this.showData = []
                            res.data.data.forEach((value, index) => {
                                if(index > 0) {
                                    this.showData.push(value)
                                }
                            })
                            this.nowData = res.data.data[0]
                            this.headerData = ['自建目录']
                            this.bus.$emit('checkFile', this.nowData)
                        }
                    })
                }
            },
        },
        beforeDestroy() {
            this.bus.$off('checkFile')
        }
    }
</script>

<style lang="scss">
  .el-scrollbar__view{
    height:100%
  }

  .el-main{
    .el-table__body-wrapper{
      height:auto !important;
      cursor: pointer !important;
    }
  }
  .el-progress-circle{
    width: 80px !important;
    height: 80px !important;
  }
  .header_title{
    .el-breadcrumb__item{
      cursor: default;
    }
  }
</style>

<style lang="scss" scoped>
  .rightullidiv{
    width: 7em;
    height: 5.5em;
    background-color: black;
    display: flex;
    justify-content: center;
    align-items: center;
    .rightulliimg {
      max-width: 7em;
      max-height: 5.5em;
    }
  }

  #menu{
    text-align:left;
    font-size:14px;
    line-height:25px;
    width:120px;
    // position:absolute;
    position: fixed;
    background:white;
    cursor:default;
    border-radius: 5px;
    border: 1px solid #999999;
    box-sizing:border-box;
    z-index:999;
    li {
      padding-left:20px;
      padding-right:5px;
      position:relative;
    }
    li:hover{
      background-color: #E9F3FD;
      color:#2A97F9
    }
  }
  .file_content{
    background-color:#F5F5F5 ;
    border-radius: 10px;
    height: 100%;
    overflow-y: auto;
  }
  .border_none{
    border: none !important;
  }
  .icon_active{
    background-color: #409EFF;
  }
  .file_header{
    display: flex;
    justify-content: space-between;
    background-color: #fdfdfd;
    border-bottom: 1px solid #ddd
  }
  .btn_box{
    background-color: white;
    border: 1px solid #ccc;
    border-right: none;
    margin-left:20px;
    height:32px;
    // width:64px;
    box-sizing: border-box;
    border-radius: 5px;
    overflow:hidden;
  }
  .btns{
    width: 32px;
    display: block;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-right: 1px solid #ccc;
    box-sizing: border-box;
    float:left;
    cursor: pointer;
  }
  .btns:hover{
    background-color: #e6e6e6
  }
  .icon_active{
    background-color: #e6e6e6
  }
  .content_main{
    height: calc(100% - 50px);
    padding: 20px 10px;
    box-sizing: border-box;
  }
  .aside_header{
    height:34px;
    line-height: 34px;
    border-bottom: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
  }
  .aside{
    border: 1px solid #ddd;
    background-color:white;
    height: 100%;
    width: 100%;
    overflow: auto;
  }
  .operation{
    margin: 0 5px
  }
  .retract, .operation{
    cursor: pointer;
    font-size: 16px !important;
  }
  .grid-content{
    height: 140px;
    width: 100%;
    display: flex;
    align-items: center;
    flex-flow: column;
    justify-content: space-around;
    cursor: pointer;
    padding: 5px;
    box-sizing: border-box;
    // overflow: hidden;
    p{
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: center;
      width:100%;
      margin: 0;
    }
  }
  .icon{
    font-size: 5em
  }
  .removeClass{
    height:0;
  }
  .custom-tree-node{
    height:26px;
  }
  .active_box{
    background-color: #cce8ff
  }
  .iconList{
    padding: 10px;
    box-sizing: border-box;
    height: 100%;
    // position: relative;
  }
  .move{
    position: absolute;
    background: #cce8ff;
    box-sizing: border-box;
  }
  .el-breadcrumb__item{
    cursor: pointer; // 鼠标点击
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 2.5em;
    height: 2.5em;
    line-height: 2.5em;
    text-align: center;
  }
  .avatar {
    width: 4em;
    height: 4em;
    display: block;
  }



  .folderName{
    user-select: none; // 防止文件名双击被选中蓝色
  }
</style>
